package com.itheima.marking_system.utils.zip.unzip;

import com.itheima.marking_system.pojo.entity.PictureEntity;
import com.itheima.marking_system.pojo.entity.ZipEntity;
import com.itheima.marking_system.utils.zip.ZipUtils;
import kotlin.Pair;


import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipUtils {

    public static Pair<List<String>, List<byte[]>> unzip(ZipEntity zipEntity) throws IOException {
//        List<PictureEntity> pictureEntities = new ArrayList<>();
        List<String> pictureNames = new ArrayList<>();
        List<byte[]> pictureDatas = new ArrayList<>();
        String suffix = zipEntity.getName().substring(zipEntity.getName().lastIndexOf("."));
        File tempZipFile = null;
        try {
            tempZipFile = File.createTempFile("temp", suffix);
            try (FileOutputStream fos = new FileOutputStream(tempZipFile)) {
                fos.write(zipEntity.getData());
            }

            // 使用 GBK 字符编码创建 ZipInputStream
            try (ZipInputStream zis = new ZipInputStream(new FileInputStream(tempZipFile), Charset.forName("GBK"))) {
                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    if (!entry.isDirectory()) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            baos.write(buffer, 0, len);
                        }
                        //TODO: 来一个复杂的，这里应该是返回一个 Pair 对象，包含图片数据和图片名称
                        pictureDatas.add(baos.toByteArray());
                        pictureNames.add(entry.getName());
                    }
                    zis.closeEntry();
                }
            }
        } catch (IOException e) {
            throw new IOException("Error while unzipping file: " + e.getMessage(), e);
        } finally {
            if (tempZipFile != null && tempZipFile.exists()) {
                tempZipFile.delete();
            }
        }
        return new Pair<>(pictureNames, pictureDatas);
    }
}
